package com.it.action;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.it.biz.CourseBiz;
import com.it.biz.GradeBiz;
import com.it.pojo.Courses;
import com.it.pojo.CoursesExample;
import com.it.pojo.Grade;
import com.jkoss.pojo.AjaxReturn;
import com.jkoss.pojo.GradeDetail;
import com.jkoss.tool.Page;

@Controller
public class GradeAction {
	@Resource
	private GradeBiz gbiz;
	
	@Resource
	private CourseBiz courseBiz;
	/**
	 * 该类用于listGrade.jsp的增删改查
	 * */
	
	/*
	 * 获取所有的成绩记录
	 */
	@RequestMapping("findGrade.do")
	public String findGrade(Model model,Page page) {
		List<GradeDetail> list = new ArrayList<>();
		if(page==null) {
			page = new Page<Grade>();
		}
		List<Grade> grades = gbiz.findGrade(page);
		List<Courses> courses = courseBiz.selectByExample(new CoursesExample());
		for(Grade g:grades) {
			for(Courses cou:courses) {
				GradeDetail grade = new GradeDetail();
				if(g.getCid()==cou.getCid()) {
					grade.setCourse(cou);
					grade.setGrade(g);
					list.add(grade);
				}
			}
		}
		
		page.setResults(list);
		model.addAttribute("page", page);
		return "grade/listGrade.jsp";
	}
	/*
	 * 增加一条成绩记录
	 */
	@RequestMapping("addGrade.do")
	public String addCourse(Model model,Grade grade) {
		if(grade!=null) {
			gbiz.insert(grade);
		}
		return findGrade(model,null);
		
	}
	/*
	 * 根据主键信息删除成绩记录
	 */
	@RequestMapping("delGrade.do")
	public String deleteByExample(Model model,Integer gid) {
		gbiz.deleteByPrimaryKey(gid);
		return findGrade(model, null);
	}
	/*
	 * 根据主键更新成绩信息
	 */
	@RequestMapping("updGrade.do")
	public String updGrade(Model model,Grade grade) {
		if(grade!=null) {
			gbiz.updateByPrimaryKey(grade);
			return findGrade(model, null);
		}else
			System.out.println("fail");
		return findGrade(model, null);
		
	}

	/*
	 * ajax异步传输数据
	 */
	@RequestMapping("ajOneGrade.do")
	@ResponseBody
	public AjaxReturn ajOneCou(Integer gid) {
		AjaxReturn ajaxReturn = new AjaxReturn();
		Grade grade = gbiz.selectByPrimaryKey(gid);
		if(grade!=null) {
			ajaxReturn.setHead("ok");
			ajaxReturn.setBody(grade);
		}else {
			ajaxReturn.setHead("err");
		}
		return ajaxReturn;
	}
}
